package com.jgp.config;

import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Whitelist;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 项目   epidemic-situation-system
 * 作者   loufei
 * 时间   2020-02-27
 */
@Log4j2
public class XssAndSqlHttpServletRequestWrapper extends HttpServletRequestWrapper {
	
	/**
	 * 预编译SQL过滤正则表达式
	 */
	private Pattern sqlPattern = Pattern.compile(
	      "(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|(\\b(select|update|and|or|delete|insert|trancate|char|into|substr|ascii|declare|exec|count |master|into|drop|execute)\\b)", Pattern.CASE_INSENSITIVE);
	
	/**
	 * Constructs a request object wrapping the given request.
	 *
	 * @param request The request to wrap
	 * @throws IllegalArgumentException if the request is null
	 */
	public XssAndSqlHttpServletRequestWrapper(HttpServletRequest request) {
		super(request);
	}
	
	@Override
	public String getHeader(String name) {
		String strHeader = super.getHeader(name);
		if (StringUtils.isEmpty(strHeader)) {
			return strHeader;
			
		}
		return filter(super.getHeader(name));
	}
	
	@Override
	public String getParameter(String name) {
		String strParameter = super.getParameter(name);
		if (StringUtils.isEmpty(strParameter)) {
			return strParameter;
		}
		return filter(super.getParameter(name));
	}
	
	@Override
	public String[] getParameterValues(String name) {
		String[] values = super.getParameterValues(name);
		if (values == null) {
			return values;
		}
		int length = values.length;
		String[] escapseValues = new String[length];
		for (int i = 0; i < length; i++) {
			//过滤一切可能的xss攻击字符串
			escapseValues[i] = filter(values[i]);
			if (!StringUtils.equals(escapseValues[i], values[i])) {
				log.info("<xss and sql>字符串过滤前：" + values[i] + "\t" + "过滤后：" + escapseValues[i]);
			}
		}
		return escapseValues;
	}
	
	private String filter(String v) {
		v = Jsoup.clean(v,"", Whitelist.relaxed(),new Document.OutputSettings().prettyPrint(false)).trim();
		if (v != null) {
			String resultVal = v;
			Matcher matcher = sqlPattern.matcher(resultVal);
			if (matcher.find()) {
				resultVal = matcher.replaceAll("");
			}
			if (!resultVal.equals(v)) {
				return "";
			}
			return resultVal;
		}
		return null;
	}
	
}
